package com.ruoyi.generator.service;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.generator.entity.*;
import com.ruoyi.generator.entity.bo.PlanAssociationBO;
import com.ruoyi.generator.mapper.ManagementMapper;
import com.ruoyi.generator.mapper.PlanAssociationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ManagementServiceImpl implements ManagementService {


    @Autowired
    private ManagementMapper managementMapper;

    @Autowired
    private PlanAssociationMapper planAssociationMapper;

    @Override
    public List<Region> selectRegionList(Region region) {
        return managementMapper.selectRegionList(region);
    }

    @Override
    public int addRegion(Region region) {
        return managementMapper.addRegion(region);
    }

    @Override
    public int updateRegion(Region region) {
        return managementMapper.updateRegion(region);
    }

    @Override
    public int addEditRegion(Equipment equipment) {
        return managementMapper.addEquipment(equipment);
    }

    @Override
    public int updateEquipment(Equipment equipment) {
        return managementMapper.updateEquipment(equipment);
    }

    @Override
    public List<Equipment> selectEquipmentList(Equipment equipment) {
        return managementMapper.selectEquipmentList(equipment);
    }

    @Override
    public int addEditTask(Task task) {
        return managementMapper.addTask(task);
    }

    @Override
    public int updateTask(Task task) {
        return managementMapper.updateTask(task);
    }

    @Override
    public List<Task> selectTaskList(Task task) {
        return managementMapper.selectTaskList(task);
    }

    @Override
    public List<MaintenancePlan> selectMaintenancePlanList(MaintenancePlan maintenancePlan) {
        return managementMapper.selectMaintenancePlanList(maintenancePlan);
    }

    @Transactional
    @Override
    public void addRegions(List<Region> regions) {
        managementMapper.addRegions(regions);
    }

    @Transactional
    @Override
    public void addEditTasks(List<Task> tasks) {
        managementMapper.addEditTasks(tasks);
    }

    @Transactional
    @Override
    public void addMaintenancePlans(List<MaintenancePlan> maintenancePlanList) {
        managementMapper.addMaintenancePlans(maintenancePlanList);
    }
    @Transactional
    @Override
    public void addEditEquipments(List<Equipment> equipments) {
        managementMapper.addEditEquipments(equipments);
    }

    /**
     * 查询区域列表
     *
     * @return
     */
    @Override
    public List<Region> getRegionList() {
        List<Region> regionList = managementMapper.selectRegionList();
        return regionList;
    }

    /**
     * 根据区域ID获取设备信息
     *
     * @param equipment
     * @return
     */
    @Override
    public List<Equipment> getEquipmentList(Equipment equipment) {
        List<Equipment> equipmentList = managementMapper.selectEquipmentList(equipment);
        return equipmentList;
    }

    /**
     * 根据设备ID获取任务信息
     *
     * @param task
     * @return
     */
    @Override
    public List<Task> getTaskList(Task task) {
        List<Task> tasks = managementMapper.selectTaskList(task);
        return tasks;
    }

    @Transactional
    @Override
    public void performBatchOperations(List<Region> regions, List<Equipment> equipments, List<Task> tasks, List<MaintenancePlan> maintenancePlanList) {
        try {
            // 开启事务
            clearAllTables();  // 清空已有数据，并禁用外键约束

            // 批量插入区域数据
            if (regions != null && !regions.isEmpty()) {
                addRegions(regions);
            } else {
                throw new ServiceException("批量操作失败：插入的区域数据为空！");
            }

            // 验证区域数据插入正确
            if (!validateAreaIds(regions)) {
                throw new ServiceException("批量操作失败：区域数据验证失败，无法匹配插入的 'area_id'");
            }

            // 批量插入设备数据
            if (equipments != null && !equipments.isEmpty()) {
                addEditEquipments(equipments);
            }

            // 验证设备表外键 `area_id`
            if (!validateEquipmentAreaIds(equipments)) {
                throw new ServiceException("批量操作失败：设备数据验证失败，存在不匹配的 'area_id'");
            }

            // 批量插入任务数据
            if (tasks != null && !tasks.isEmpty()) {
                addEditTasks(tasks);
            }
            // 批量插入保养数据
            if (maintenancePlanList != null && !maintenancePlanList.isEmpty()) {
                addMaintenancePlans(maintenancePlanList);
            }

            List<PlanAssociationBO> planAssociationBOS = planAssociationMapper.selectPlanAssociationInfo();

            List<PlanAssociation> planAssociationList = new ArrayList<>();
            for (PlanAssociationBO planAssociationBO : planAssociationBOS) {
                PlanAssociation planAssociation = new PlanAssociation();
                planAssociation.setAreaId(planAssociationBO.getAreaId());
                planAssociation.setEquipmentId(planAssociationBO.getEquipmentId());
                planAssociation.setTaskId(planAssociationBO.getTaskId());
                planAssociation.setScheduleId(planAssociationBO.getScheduleId());
                planAssociationList.add(planAssociation);
            }
            if (planAssociationList != null && !planAssociationList.isEmpty()){
                planAssociationMapper.insertPlanAssociation(planAssociationList);
            }

        } catch (Exception e) {
            // 捕获异常并抛出事务回滚
            throw new ServiceException("批量操作失败，事务已回滚: " + e.getMessage());
        }
    }
    // 验证插入的区域 ID 是否成功写入数据库
    private boolean validateAreaIds(List<Region> regions) {
        List<String> areaIds = regions.stream().map(Region::getAreaId).collect(Collectors.toList());
        List<String> storedIds = managementMapper.getAreaIds(areaIds);
        return storedIds.containsAll(areaIds);
    }
    // 验证设备表中的 area_id 是否在区域表中存在
    private boolean validateEquipmentAreaIds(List<Equipment> equipments) {
        List<String> areaIds = equipments.stream().map(Equipment::getAreaId).collect(Collectors.toList());
        List<String> storedIds = managementMapper.getAllAreaIds(); // 查询所有区域表的 area_id
        return storedIds.containsAll(areaIds);
    }
    @Transactional
    public void clearAllTables() {
        managementMapper.deleteWushuiTask(); // 先清空任务表
        managementMapper.deleteWushuiEquipment(); // 再清空设备表
        managementMapper.deleteWushuiArea(); // 最后清空区域表
    }


}
